package com.sirui.x.io.bio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sirui.x.util.StreamUtils;

public class SocketRunnable implements Runnable{

	private static final Logger logger = LoggerFactory.getLogger(SocketRunnable.class);
	
	private Socket socket;
	
	public SocketRunnable(Socket socket) {
		super();
		this.socket = socket;
	}

	@Override
	public void run() {
		try(InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream()){
			byte[] bytes = StreamUtils.copyToByteArrayMax4096(is);
			String msg = Serializ.deserialization(bytes);
			logger.info("server recieve: {}", msg);
			
			String sendMsg = "Status Code: 200 OK\nContent-Type: application/json\n{\"status\":\"yes\"}";
			byte[] sendMsgByte = Serializ.serialization(sendMsg);
			StreamUtils.copyMax4096(new ByteArrayInputStream(sendMsgByte), os);
			logger.info("server send: ", sendMsg);
		}catch (Exception e) {
			logger.error("", e);
		}finally {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}
		
	}
	
}
